#include "stdafx.h"
#include "BasicMemDC.h"

namespace BasicSkinView
{
	CBasicMemDC::CBasicMemDC()
		:m_hMem(NULL)
		,m_cx(0)
		,m_cy(0)
		,m_hBitmap(NULL)
		,m_pBits(NULL)
	{
	}

	CBasicMemDC::~CBasicMemDC()
	{
		if(m_hMem)
			::DeleteDC(m_hMem);
		if(m_hBitmap)
			::DeleteObject(m_hBitmap);
		m_hBitmap = NULL;
		m_hMem = NULL;
	}

	bool CBasicMemDC::CreateDIB(HDC hdc, int cx, int cy)
	{
		if(m_hBitmap)
		{
			::DeleteObject(m_hBitmap);
			m_hBitmap = NULL;
		}

		m_bmpHeader.biSize = sizeof(BITMAPINFOHEADER);
		m_bmpHeader.biBitCount = 32;
		m_bmpHeader.biCompression = BI_RGB;
		m_bmpHeader.biWidth = cx;
		m_bmpHeader.biHeight = -cy;
		m_bmpHeader.biPlanes = 1;
		m_hBitmap = CreateDIBSection(hdc,(BITMAPINFO*)&m_bmpHeader, DIB_RGB_COLORS, (void**)&m_pBits, NULL, 0 );
		if( m_hMem )
			::SelectObject(m_hMem, m_hBitmap);

		return m_hBitmap != NULL;

	}

	bool CBasicMemDC::SetMemSize(HDC hdc, int cx, int cy)
	{
		if(m_hMem == NULL)
		{
			m_cx = cx;
			m_cy = cy;

			m_hMem = ::CreateCompatibleDC(hdc);
			
			CreateDIB(hdc, cx, cy);
			ClearRect(0,0,cx,cy);
			return true;
		}

		if(m_cx == cx && m_cy == cy)
			return false;

		m_cx = cx;
		m_cy = cy;

		CreateDIB(hdc,cx,cy);
		ClearRect(0,0,cx,cy);
		return true;
	}

	void CBasicMemDC::ClearRect(int x, int y, int cx, int cy)
	{
		if(x<0)
			x = 0;
		if(y<0)
			y = 0;
		if(cx<0)
			cx = 0;
		if(cy<0)
			cy = 0;

		if(!m_pBits)
			return;
	
		for(int i=x; i<x+cx && i<m_bmpHeader.biWidth; i++)
		{
			for(int j=y; j<y+cy && j<-m_bmpHeader.biHeight; j++)
			{
				DWORD* pSrc = (DWORD*)m_pBits;
				pSrc += j*m_bmpHeader.biWidth+i;
				*pSrc = 0;
			}
		}

	}

	void CBasicMemDC::Invert(int x, int y, int cx, int cy)
	{
		PatBlt(m_hMem,x,y,cx,cy,PATINVERT);
	}
}